/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package etherblocks.mods.survival.entitysystem.systems;

import java.util.List;
import etherblocks.game.entitysystem.*;
import etherblocks.game.entitysystem.components.*;
import etherblocks.mods.survival.entitysystem.components.*;

/**
 *
 * @author Philipp
 */
public class AggroSystem implements EntitySystem
{

    public void onNextFrameCalculation(EntityMap entityMap, float lastTimePerFrame) {
        List<Entity> entities = entityMap.getEntities(AggroComponent.class);
        List<Entity> targets = entityMap.getEntities(CanBeAttackedComponent.class);
        
        for(Entity entity : entities)
        {
            for(Entity target : targets)
            {
                if(inTargetRange(entity, target))
                {
                    entity.clearComponent(AggroComponent.class);
                    entity.setComponent(new HasTargetComponent(target.getID()));
                    break;
                }
            }
        }
    }
        
    private boolean inTargetRange(Entity entity, Entity target) {
        LocationComponent a = entity.getComponent(LocationComponent.class);
        LocationComponent b = target.getComponent(LocationComponent.class);
        if(a == null || b == null)
        {
            return false;
        }
        float range = entity.getComponent(AggroComponent.class).getAggroRange();
        return a.getLocation().distanceSquared(b.getLocation()) <= range * range;
    }
    
}
